//
//  ESignAssistFVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2022/8/23.
//  Copyright © 2022 zwb. All rights reserved.
//

import UIKit

class ZyaESignAssistFVC: GlobalFormVC,operatable,refreshable,DateWidgetableOK,KSImageUtilDelegate {
    var sectionx_1 :ItemSectionView = {
        let v = ItemSectionView()
        v.lab.text =  "出库附件"
        v.btn.isHidden = true
        v.backgroundColor = .white
        return v
    }()
    var sectionx_2 :ItemSectionView = {
        let v = ItemSectionView()
        v.lab.text =  "发票附件"
        v.btn.isHidden = true
        v.backgroundColor = .white
        return v
    }()
    var sectionx_3 :ItemSectionView = {
        let v = ItemSectionView()
        v.lab.text =  "合同附件"
        v.btn.isHidden = true
        v.backgroundColor = .white
        return v
    }()
    var item1 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "合同号",appearance:appe )
        v.disabled = true
        return v
    }()
    
    var imageUtil2:KSImageSelectUtil?
    var imageUtil3:KSImageSelectUtil?
    var attr = [VideoImg]()
    var attr2 = [VideoImg]()
    var attr3 = [VideoImg]()
    
    var z_ht_no = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "附件管理"
        
        
        
        if self.excuteType == .add || excuteType == .fix {
            let saveBtn = UIBarButtonItem(title: "保存", style: .done, target: self, action: #selector(saveAction))
            self.navigationItem.rightBarButtonItem = saveBtn
        }
        
        // 创建调度组
        let workingGroup = DispatchGroup()
        
        
        // 入组
        workingGroup.enter()
        KSNetwork.shared.doRequest(API.eSignGetFileList(s_type: "outLibrary", z_ht_no: z_ht_no)) { (data:BaseResult<ZyaEsFileModel>) in
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    
                    self.attr.removeAll()
                    for item in infos {
                        var ttt:SourType = .file
                        if item.pic_url.unwrap.contains("png") || item.pic_url.unwrap.contains("jpg") ||
                            item.pic_url.unwrap.contains("jpeg") {
                            ttt = .image
                        }
                        var one = VideoImg(type: ttt, idkey: item.id_key.unwrap, url: configURLOK(latter: item.pic_url.unwrap), name: item.pic_name.unwrap)
                        if ttt == .image {
                            one.image = getPicture(url: one.url.unwrap)
                        }
                        self.attr.append(one)
                    }
                    
                    
                    // 出组
                    workingGroup.leave()
                }
                
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
        // 入组
        workingGroup.enter()
        KSNetwork.shared.doRequest(API.eSignGetFileList(s_type: "invoice", z_ht_no: z_ht_no)) { (data:BaseResult<ZyaEsFileModel>) in
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    
                    self.attr2.removeAll()
                    for item in infos {
                        var ttt:SourType = .file
                        if item.pic_url.unwrap.contains("png") || item.pic_url.unwrap.contains("jpg") ||
                            item.pic_url.unwrap.contains("jpeg") {
                            ttt = .image
                        }
                        var one = VideoImg(type: ttt, idkey: item.id_key.unwrap, url: configURLOK(latter: item.pic_url.unwrap), name: item.pic_name.unwrap)
                        if ttt == .image {
                            one.image = getPicture(url: one.url.unwrap)
                        }
                        self.attr2.append(one)
                    }
                    
                    
                    // 出组
                    workingGroup.leave()
                }
                
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
        // 入组
        workingGroup.enter()
        KSNetwork.shared.doRequest(API.eSignGetFileList(s_type: "contract", z_ht_no: z_ht_no)) { (data:BaseResult<ZyaEsFileModel>) in
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    
                    self.attr3.removeAll()
                    for item in infos {
                        var ttt:SourType = .file
                        if item.pic_url.unwrap.contains("png") || item.pic_url.unwrap.contains("jpg") ||
                            item.pic_url.unwrap.contains("jpeg") {
                            ttt = .image
                        }
                        var one = VideoImg(type: ttt, idkey: item.id_key.unwrap, url: configURLOK(latter: item.pic_url.unwrap), name: item.pic_name.unwrap)
                        if ttt == .image {
                            one.image = getPicture(url: one.url.unwrap)
                        }
                        self.attr3.append(one)
                    }
                    
                    
                    // 出组
                    workingGroup.leave()
                }
                
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
        
        
        // 调度组里的任务都执行完毕
        workingGroup.notify(queue: .main) {
            self.configView()
            self.configAction()
            self.configDataSource()
            self.tableVw.reloadData()
        }
        
        
        
        
    }
    
    func configView() {
        bg.add(item1)
        let viewFlag:ImgViewType = (excuteType == .view) ? .viewOnly : .editable
        bg.addSection(sectionx_1)
        
        imageUtil = KSImageSelectUtil(frame: CGRect(x:0,y:sectionx_1.frame.maxY,width:bg.ks_width ,height:imgHeight),httpHeader: "",numberOfRow: 5,picType: [.takePicture,.albumPicture,.albumVideo,.allfile],viewType:viewFlag)
        imageUtil?.ksDelegate = self
        bg.addv(view:imageUtil!)
        self.imageUtil!.newestShow(arr: self.attr)
        bg.addSection(sectionx_2)
        imageUtil2 = KSImageSelectUtil(frame: CGRect(x:0,y:sectionx_2.frame.maxY,width:bg.ks_width ,height:imgHeight),httpHeader: "",numberOfRow: 5,picType: [.takePicture,.albumPicture,.albumVideo,.allfile],viewType:viewFlag)
        imageUtil2?.ksDelegate = self
        bg.addv(view:imageUtil2!)
        self.imageUtil2!.newestShow(arr: self.attr2)
        bg.addSection(sectionx_3)
        imageUtil3 = KSImageSelectUtil(frame: CGRect(x:0,y:sectionx_3.frame.maxY,width:bg.ks_width ,height:imgHeight),httpHeader: "",numberOfRow: 5,picType: [.takePicture,.albumPicture,.albumVideo,.allfile],viewType:viewFlag)
        imageUtil3?.ksDelegate = self
        bg.addv(view:imageUtil3!)
        self.imageUtil3!.newestShow(arr: self.attr3)
        header.ks_height = bg.frame.maxY
        self.tableVw.tableHeaderView = header
    }
    func configAction() {
        
    }
    
    
    func configDataSource() {
        item1.setVal(z_ht_no)
    }
    
    //
    //    func dealBeforeAddImages(_ util: KSImageSelectUtil, imgs: [UIImage]) -> [UIImage] {
    //        return  imgs.compactMap { $0.drawTextInImage(waterStrings: [waterMarkStringType(text: "\(USERINFO.mOrgNm.unwrap)\n\(Date.nowTimeToSecond)\n\(LocationTool.shared.address)", textColor: .red,  position: .bottomLeft)]) }
    //    }
    func addImages(_ util: KSImageSelectUtil, imgvideos: [VideoImg]) {
        if util == self.imageUtil {
        self.attr += imgvideos
        } else if util == self.imageUtil2 {
            self.attr2 += imgvideos
        } else if util == self.imageUtil3 {
            self.attr3 += imgvideos
        }
    }
    func addFiles(_ util: KSImageSelectUtil, files: [VideoImg]) {
        if util == self.imageUtil {
        self.attr += files
        } else if util == self.imageUtil2 {
            self.attr2 += files
        } else if util == self.imageUtil3 {
            self.attr3 += files
        }
    }
    func deleteImage(_ util: KSImageSelectUtil, index: Int) {
        if util == self.imageUtil {
            let one = self.attr[index]
            if one.idkey.unwrap.isEmpty {
                self.attr.remove(at: index)
                self.imageUtil!.deleteLocalImg(tag: index)
            } else {
                alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                    KSNetwork.shared.doRequest(API.eSignDeleteFile(id: one.idkey.unwrap)) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            KSToast("删除成功")
                            self.attr.remove(at: index)
                            self.imageUtil!.deleteLocalImg(tag: index)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                    
                })])
                
            }
        } else if util == self.imageUtil2 {
            let one = self.attr2[index]
            if one.idkey.unwrap.isEmpty {
                self.attr2.remove(at: index)
                self.imageUtil2!.deleteLocalImg(tag: index)
            } else {
                alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                    KSNetwork.shared.doRequest(API.eSignDeleteFile(id: one.idkey.unwrap)) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            KSToast("删除成功")
                            self.attr2.remove(at: index)
                            self.imageUtil2!.deleteLocalImg(tag: index)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                    
                })])
                
            }
        } else if util == self.imageUtil3 {
            let one = self.attr3[index]
            if one.idkey.unwrap.isEmpty {
                self.attr3.remove(at: index)
                self.imageUtil3!.deleteLocalImg(tag: index)
            } else {
                alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                    KSNetwork.shared.doRequest(API.eSignDeleteFile(id: one.idkey.unwrap)) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            KSToast("删除成功")
                            self.attr3.remove(at: index)
                            self.imageUtil3!.deleteLocalImg(tag: index)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                    
                })])
                
            }
        }
        
    }
    
    // MARK: - 提交
    @objc func saveAction() {
        // 创建调度组
        let workingGroup = DispatchGroup()
        
        //        传类型（出库：outLibrary、发票：invoice、合同：contract
        
        
        let unUploadF = self.attr.filter{ $0.idkey.unwrap == "" }
        let unUploadF2 = self.attr2.filter{ $0.idkey.unwrap == "" }
        let unUploadF3 = self.attr3.filter{ $0.idkey.unwrap == "" }
        guard unUploadF.count > 0 || unUploadF2.count > 0 || unUploadF3.count > 0 else {
            KSToast("未新增文件")
            return
        }
        if unUploadF.count > 0 {
            // 入组
            workingGroup.enter()
            KSNetwork.shared.doRequest(API.eSignUploadFiles(s_type: "outLibrary", z_ht_no: z_ht_no, files: unUploadF)) {  (data:BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    // 出组
                    workingGroup.leave()
                } else {
                    
                    KSToast(data.errorCombine.unwrap)
                    
                }
                
            }
        }
       
        
        if unUploadF2.count > 0 {
            // 入组
            workingGroup.enter()
            KSNetwork.shared.doRequest(API.eSignUploadFiles(s_type: "invoice", z_ht_no: z_ht_no, files: unUploadF2)) {  (data:BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    // 出组
                    workingGroup.leave()
                    
                } else {
                    
                    KSToast(data.errorCombine.unwrap)
                    
                }
                
            }
        }
        
        
        if unUploadF3.count > 0 {
            // 入组
            workingGroup.enter()
            KSNetwork.shared.doRequest(API.eSignUploadFiles(s_type: "contract", z_ht_no: z_ht_no, files: unUploadF3)) {  (data:BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    // 出组
                    workingGroup.leave()
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
               
            }
        }
        // 调度组里的任务都执行完毕
        workingGroup.notify(queue: .main) {
            
            self.backAction()
            
        }
        
        
    }
    
    func backAction() {
        if let clo = self.refreshClosure {
            clo()
        }
        self.navigationController?.popViewController(animated: true)
    }
    
    
    
}
